'use client';

import { useToast } from '@/hooks/use-toast';
import { authClient } from '@/lib/auth-client';
import { result } from '@/lib/utils';
import { queryClient } from '@/providers/trpc-provider';
import { useRouter } from 'next/navigation';
import ConfirmButton from './confirm-button';

export default function SignOut({ button }: { button: React.ReactNode }) {
  const { toast } = useToast();
  const { replace } = useRouter();

  return (
    <ConfirmButton
      title="退出登录"
      description="确认退出登录吗?"
      button={button}
      onClick={async () => {
        try {
          const { error } = await authClient.signOut();
          if (error) {
            toast({
              title: error.message,
              variant: 'destructive',
            });
            return result(error, error.message ?? '退出登录失败');
          }
          toast({
            title: '退出登录成功',
          });
          queryClient.clear();
          replace('/login');
          return result();
        } catch (error: any) {
          console.error(error);
          return result(error, error.message ?? '退出登录失败');
        }
      }}
    />
  );
}
